package com.freely.web.action;

import java.io.IOException;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freely.domain.ResponseMessage;
import com.freely.domain.User;
import com.freely.service.UserService;
import com.freely.service.VerificationService;
import com.freely.util.Base64Util;
import com.freely.util.HttpUtil;
import com.freely.util.ResponseMessageUtil;
import com.freely.util.VerificationUtil;
import com.opensymphony.xwork2.ActionSupport;

public class VerificationAction extends ActionSupport {
	private VerificationService verificationService;
	private UserService userService;
	
	/**
	 * 注册或登录时客户端发送设备唯一码请求验证码 后台将设备唯一码与验证码作为键值对存储在ServletContext
	 * 
	 * @throws IOException
	 */
	public void request() throws IOException {
		JSONObject object = HttpUtil.parseJSON("验证码获取失败,请重新获取");
		if(object == null) {
			return;
		}
		// 验证发送数据是否包含设备码
		String device_code = object.getString("device_code");
		if (device_code == null || device_code.trim().length() == 0) {
			ResponseMessageUtil.response(false, "验证码获取失败,请重新获取");
			return;
		}
		// 生成验证码图片并转为为base64编码发送给客户端
		VerificationUtil util = new VerificationUtil();
		byte[] imageData = util.getImageByte();
		String encodeData = Base64Util.encode(imageData);
		ServletActionContext.getServletContext().setAttribute(device_code, util.getText());
		ResponseMessageUtil.response(true, encodeData);
	}

	/**
	 * 注册或登录时后台验证客户端发过来的设备唯一码与验证码来验证验证码是否正确
	 * @throws IOException
	 */
	public void check() throws IOException {
		JSONObject object = HttpUtil.parseJSON("验证码为空，请重新输入");
		if(object == null) {
			return;
		}
		// 验证验证码
		String device_code = object.getString("device_code");
		String verification_code = object.getString("verification_code");
		if (device_code == null || device_code.trim().length() == 0 ||
				verification_code == null || verification_code.trim().length() == 0) {
			ResponseMessageUtil.response(false, "验证码为空，请重新输入");
			return;
		}
		ServletContext context = ServletActionContext.getServletContext();
		String code = (String) context.getAttribute(device_code);
		if(code == null || !code.equals(verification_code)) {
			ResponseMessageUtil.response(false, "验证码错误，请重新输入");
			return;
		}
		context.setAttribute(device_code, true);
		ResponseMessageUtil.response(true, "验证码正确");
	}
	
	/**
	 * 发送邮件
	 * @throws IOException
	 */
	public void getBackPasswordRequest() throws IOException {
		JSONObject object = HttpUtil.parseJSON("邮箱不正确,请重试");
		if(object == null) {
			return;
		}
		// 验证邮箱格式是否正确
		String email = (String) object.get("user_email");
		if(email == null || email.trim().length() == 0 || 
				!email.matches("^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$")) {
			ResponseMessageUtil.response(false, "邮箱不正确,请重试");
			return;
		}
		// 判断是否存在某用户使用该邮箱
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("user_email", email));
		List<User> result = userService.findByCondition(criteria);
		if(result == null) {
			ResponseMessageUtil.response(false, "邮箱不正确,请重试");
			return;
		}
		// 发送邮件
		try {
			verificationService.sendMail(email);
		} catch (MessagingException e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "邮箱不正确,请重试");
			return;
		}
		ResponseMessageUtil.response(true, "验证码已发送,请登录邮箱查看");
	}
	
	/**
	 * 验证找回密码验证码是否正确
	 * @throws IOException 
	 */
	public void getBackPasswordResponse() throws IOException {
		JSONObject object = HttpUtil.parseJSON("验证码错误,请重试");
		if(object == null) {
			return;
		}
		// 验证验证码
		String user_email = object.getString("user_email");
		String verification_code = object.getString("verification_code");
		if(user_email == null || user_email.trim().length() == 0 ||
				verification_code == null || verification_code.trim().length() == 0) {
			ResponseMessageUtil.response(false, "验证码错误,请重试");
			return;
		}
		ServletContext context = ServletActionContext.getServletContext();
		String verification = (String) context.getAttribute(user_email);
		if(verification_code.equals(verification)) {
			context.removeAttribute(user_email);
			ResponseMessageUtil.response(true, "验证成功");
			return;
		}
		ResponseMessageUtil.response(false, "验证码错误,请重试");
	}
}
